<template>
  <div>
    <h1>Hello{{ title }}</h1>
    <ul>
      <li v-for="(good, index) in goods" :key="index">
        {{ good.text }}
        |
        {{ good.price }}
        <button @click="addCart(index)">添加购物车</button>
      </li>
    </ul>
    <Cart :data="cart" @add="onAdd" @reduce="onReduce" />
  </div>
</template>
<script>
import Cart from "./components/Cart";
export default {
  components: {
    Cart,
  },
  data() {
    return {
      title: "开课吧",
      goods: [
        { text: "百万年薪架构师", price: 100 },
        { text: "Web全栈", price: 80 },
        { text: "JS高级", price: 70 },
      ],
      cart: [],
    };
  },
  methods: {
    addCart(i) {
      console.log(i);
      let item = this.goods[i];
      let good = this.cart.find((v) => v.text == item.text);
      if (good) {
        good.count++;
      } else {
        this.cart.push({ ...item, count: 1 });
      }
    },
    onAdd(index) {
      console.log(index);
      this.cart[index].count++;
    },
    onReduce(index) {
      if (this.cart[index].count > 1) {
        this.cart[index].count--;
      } else {
        this.cart.splice(index, 1);
      }
    },
  },
};
</script>
<style lang="less">
h1 {
  color: red;
}
</style>
